package com.lq.filestudy.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lq.filestudy.dao.AriNewsDao;
import com.lq.filestudy.entity.AriNews;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import static org.springframework.core.io.buffer.DataBufferUtils.readInputStream;

@RestController
@RequestMapping
@Slf4j

public class ImgChangeController {


    @Resource
    private AriNewsDao ariNewsDao;
  private static String imgTitle = "src=";
    private static String altTitle = "alt";


    private static String fileAddress = "D:\\ari_tech_info\\defaultBucket\\";

    private static String FILES = "files/";

    private static final String niginxUrl = "http://127.0.0.1:9002";



    @GetMapping("/dealData")
    @Transactional
    public void dealData(){

        // 7 24 23 51 73 118 142 147 191
        List<AriNews> list = ariNewsDao.selectList(new LambdaQueryWrapper<AriNews>().ge(AriNews::getId,236));

        //查询全部数据 进行数据存储到本地地址
        for (int i = 0; i < list.size(); i++) {
            AriNews ariNews = list.get(i);
            String content = ariNews.getContent();
            String content2 = ariNews.getContent2();
            Long id = ariNews.getId();
            List<String> urlList = getUrlList(content,id);
            Boolean isChange = false;
            for (String url:urlList){
                if (url.contains(niginxUrl)){
                    isChange = true;
                }
            }
        if(isChange){
            //替换过不做处理
            continue;
        }
            //进行替换
            Map<String, String> mapUrl = downLoad(urlList);

            urlList.forEach(oriUrl->{
                String changeUrl = mapUrl.get(oriUrl);
                content.replace(oriUrl,changeUrl);
                content2.replace(oriUrl,changeUrl);
                log.info("id->{}，替换后的 url->{}",ariNews.getId(),changeUrl);
            });

            ariNews.setContent(content);
            ariNews.setContent2(content2);
            ariNewsDao.updateById(ariNews);
        }


    }


    private static List<String> getUrlList(String oriContent,Long id) {
        List<String> urlList = new ArrayList<>();
        for (int i = 0; i < oriContent.length(); i++) {

            if (oriContent.regionMatches(true, i, imgTitle, 0, 4)) {
                String tempSring = oriContent.substring(i + 5);
                String url = tempSring.substring(0, tempSring.indexOf(altTitle) - 2);
                log.info("id->{},拿到的 url->{}",id,url);
                urlList.add(url);
            }

        }
        return urlList;
    }

    private static Map<String, String> downLoad(List<String> oriList) {
        HashMap<String, String> urlMap = new HashMap<>();
        if (CollectionUtils.isEmpty(oriList)) {
            return urlMap;
        } else {
            oriList.stream().parallel().forEach(oriUrl -> {

                try {
                  urlMap.put(oriUrl,download(oriUrl, fileAddress))  ;
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            });

        }

        return urlMap;
    }


    /**
     * 文件下载到指定路径
     *
     * @param urlString 链接
     * @param savePath  保存路径
     * @throws Exception
     */
    public static String download(String urlString, String savePath) throws Exception {
        // 构造URL
        URL url = new URL(urlString);

        url.toString().replaceAll("\r|\n","" );
        //打开连接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //睡1秒
        //Thread.sleep(1000);
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
        //设置请求方式为"GET"
        conn.setRequestMethod("GET");
        //超时响应时间为10秒
        conn.setConnectTimeout(10 * 1000);
        //通过输入流获取图片数据
        InputStream is = conn.getInputStream();
        //得到图片的二进制数据，以二进制封装得到数据，具有通用性
        byte[] data = readInputStream(is);

        String sufixx = ".webp";
        String fileName = UUID.randomUUID().toString().replaceAll("-", "") + sufixx;


        //创建一个文件对象用来保存图片，默认保存当前工程根目录，起名叫Copy.jpg
        File imageFile = new File(savePath + fileName);

        //创建输出流
        FileOutputStream outStream = new FileOutputStream(imageFile);
        //写入数据
        outStream.write(data);
        //关闭输出流，释放资源
        outStream.close();
        fileName = niginxUrl+"/"+FILES+fileName;
        return fileName;
    }


    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        //创建一个Buffer字符串
        byte[] buffer = new byte[6024];
        //每次读取的字符串长度，如果为-1，代表全部读取完毕
        int len;
        //使用一个输入流从buffer里把数据读取出来
        while ((len = inStream.read(buffer)) != -1) {
            //用输出流往buffer里写入数据，中间参数代表从哪个位置开始读，len代表读取的长度
            outStream.write(buffer, 0, len);
        }
        //关闭输入流
        inStream.close();
        //把outStream里的数据写入内存
        return outStream.toByteArray();
    }


}
